<template>
	<view class="community-container">
		<view class="top">
			<view class="text">
				<uni-easyinput type="textarea" v-model="content" placeholder="分享你的想法..." :maxlength="200" />
				<Image ref="imageComponent" />
				<button class="submit-btn" @click="submitBlog">发布</button>
			</view>
		</view>
		<view class="bottom">
			<view class="card" v-for="(item, index) in list" :key="index">
				<BlogCard :blog="item" />
			</view>
			<p style="text-align: center; color: #ccc;">已经到底咯~</p>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	onBeforeMount
} from 'vue';

const list = ref([]);
const content = ref('');
const imageComponent = ref(null);

const fetchData = async () => {
	try {
		// 获取所有文章内容
		const resp = await uniCloud.callFunction({
			name: 'getBlogs',
			data: {}
		});

		if (resp.result.code === 0) {
			return resp.result.data;
		} else {
			uni.showToast({
				title: resp.result.msg,
				icon: 'none'
			});
			return [];
		}
	} catch (err) {
		console.error('获取博客列表失败:', err);
		uni.showToast({
			title: '获取数据失败',
			icon: 'error'
		});
		return [];
	}
};

const submitBlog = async () => {
	try {
		if (!content.value.trim()) {
			uni.showToast({
				title: '请输入内容',
				icon: 'none'
			});
			return;
		}

		// 上传图片并获取fileID数组
		const imageFileIDs = await imageComponent.value.uploadImages();

		// 获取用户id，name
		const {
			_id,
			username
		} = uni.getStorageSync('userInfo');

		// 发布博客
		const res = await uniCloud.callFunction({
			name: 'addBlog',
			data: {
				content: content.value,
				images: imageFileIDs,
				// ... 其他需要的数据
				userId: _id,
				userName: username
			}
		});

		if (res.result.code === 0) {
			uni.showToast({
				title: '发布成功',
				icon: 'success'
			});

			// 清空内容和图片
			content.value = '';
			imageComponent.value.clearImages();

			// 刷新列表
			await fetchData();
		}
	} catch (err) {
		console.error('发布失败:', err);
		uni.showToast({
			title: '发布失败',
			icon: 'error'
		});
	}
};


onBeforeMount(async () => {
	list.value = await fetchData();
	console.log(list.value);

});
</script>

<style lang="scss" scoped>
@import "../../uni.scss";

.community-container {
	margin-bottom: 10px;
	box-sizing: border-box;

	.text {
		padding: 4px 10px;

		.submit-btn {
			margin-top: 5px;
			background-color: $base-color2 ;

			&:active {
				background-color: $btn-primary-color ;
			}
		}
	}

	.bottom {
		box-sizing: border-box;

		.card {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin: 10px auto;
		}
	}
}
</style>